<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="产品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="BOM版本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <a-input v-model="model.year"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="产品编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="产品规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="noneSpec">
              <a-input v-model="model.noneSpec"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- 子表单区域 -->
        <a-row>
          <!-- 新增 -->
          <a-col :span="12">
            <a-divider>已关联BOM</a-divider>
            <a-row>
              <a-table
                ref="table"
                size="middle"
                :scroll="{ x: true }"
                bordered
                :rowKey="(record) => record.id"
                :columns="goodsFormulaTable.formulaColumn"
                :dataSource="goodsFormulaTable.datasource"
                :pagination="false"
                :loading="goodsFormulaTable.loading"
                :customRow="rowSelectChange"
                class="j-table-force-nowrap1"
              >
                <template slot="operation" slot-scope="text, record">
                  <a-popconfirm title="确认删除?" @confirm="() => onDelete(record.id)">
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
            </a-row>
            <a-divider>所有配方列表</a-divider>
            <a-row>
              <a-col :span="6">
                <a-form-model-item label="BOM编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                  <a-input v-model="queryParam.code" placeholder="请输入BOM编号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="BOM名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                  <a-input v-model="queryParam.name" placeholder="请输入BOM名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-button @click="getFormulaDatasource" type="primary">查询</a-button>
              <a-button @click="searchReset" type="primary">重置</a-button>
            </a-row>
            <a-row>
              <a-table
                ref="table"
                size="middle"
                :scroll="{ x: true }"
                bordered
                rowKey="id"
                :columns="formulaTable.formulaColumn"
                :dataSource="formulaTable.datasource"
                :pagination="formulaTable.ipagination"
                :rowSelection="{ onChange: onSelectChange, selectedRow: onSelectRow, type: 'radio' }"
                :loading="formulaTable.loading"
                :customRow="rowSelectChange"
                class="j-table-force-nowrap1"
              >
              </a-table>
            </a-row>
          </a-col>

          <a-col :span="12">
            <!-- 表格 -->
            <a-table
              style="margin-left: 10px"
              ref="formulaDetailTable"
              bordered
              :data-source="formulaDetailTable.datasource"
              :columns="formulaDetailTable.formulaDetailColumn"
              :rowKey="(record) => record.id"
              :pagination="false"
            >
            </a-table>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <employee-list-modal ref="selectEmployee" @handlerOk="handleSelectEmployeeOk" />
  </a-spin>
</template>

<script>
import { httpAction } from '@/api/manage'
import { putAction } from '@api/manage'
import { postAction } from '@api/manage'
import { getAction } from '@api/manage'
import Big from 'big.js'
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import EditableCell from '@comp/table/EditableCell'
import EmployeeListModal from '@/components/tsl/modules/EmployeeListModal.vue'

export default {
  name: 'ErpGoodsFormulaAddForm',
  components: {
    ErpGoodsListModel,
    EditableCell,
    EmployeeListModal,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      selectedRowKeys: [],
      selectionRows: [],
      visible: false,
      modalWidth: 1250,
      category: '2',
      selectedFormularId: '',
      queryParam: {
        code: '',
        name: '',
      },
      model: {
        id: '',
        code: '',
        year: '',
        name: '',
        noneSpec: '',
      },
      goodsFormulaCon: {
        year: '',
        goodsId: '',
        formulaIds: [],
      },
      goodsFormulaTable: {
        loading: false,
        datasource: [],
        formulaColumn: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: 'BOM版本号',
            dataIndex: 'year',
          },
          {
            title: 'BOM编码',
            dataIndex: 'code',
          },
          {
            title: 'BOM号',
            dataIndex: 'no',
          },

          {
            title: 'BOM名称',
            dataIndex: 'pattern',
          },
          {
            title: '类别',
            dataIndex: 'category_dictText',
          },
          {
            title: 'BOM类型',
            dataIndex: 'materialQuality',
          },
          {
            title: '制单人',
            dataIndex: 'createByName',
            width: 150,
          },
          {
            title: '制单日期',
            dataIndex: 'createTime',
          },
          {
            title: '类别',
            dataIndex: 'type_dictText',
          },
          {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            fixed: 'right',
            scopedSlots: { customRender: 'operation' },
          },
        ],
      },
      formulaTable: {
        loading: false,
        datasource: [],
        // 表头
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['10', '30', '100'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        formulaColumn: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: 'BOM版本号',
            dataIndex: 'year',
          },
          {
            title: 'BOM编码',
            dataIndex: 'code',
          },
          {
            title: 'BOM号',
            dataIndex: 'no',
          },

          {
            title: 'BOM名称',
            dataIndex: 'pattern',
          },
          {
            title: '类别',
            dataIndex: 'category_dictText',
          },
          {
            title: 'BOM类型',
            dataIndex: 'materialQuality',
          },
          {
            title: '制单人',
            dataIndex: 'createByName',
            width: 150,
          },
          {
            title: '制单日期',
            dataIndex: 'createTime',
          },
          {
            title: '类别',
            dataIndex: 'type_dictText',
          },
        ],
      },
      formulaDetailTable: {
        loading: false,
        datasource: [],
        // 表头
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['10', '30', '100'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        formulaDetailColumn: [
          {
            title: '编号',
            dataIndex: 'detailNo',
          },
          {
            title: '物料名称',
            dataIndex: 'materialName',
          },
          {
            title: '规格',
            dataIndex: 'spec',
          },

          {
            title: 'BOM比例%',
            dataIndex: 'computingFormula',
          },
          {
            title: '实际数量',
            dataIndex: 'actualQuantity',
          },
        ],
      },

      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        style: 'width: 28%;',
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      textareaLabelCol: {
        xs: { span: 12 },
        sm: { span: 2 },
      },
      textareaWrapperCol: {
        xs: { span: 40 },
        sm: { span: 21 },
      },
      confirmLoading: false,
      validatorRules: {
        code: [{ required: true, message: '请输入编号!' }],
        name: [{ required: true, message: '请输入名称!' }],
        year: [{ required: true, message: '请输入BOM版本号!' }],
      },
      url: {
        add: '/base/erpGoodsFormulaCon/add',
        edit: '/base/erpGoods/edit',
        queryById: '/base/erpGoods/queryById',
        formulaList: '/base/erpGoodsFormula/list',
        formulaDetailList: '/base/erpGoodsFormulaDetail/queryListByIds',
        queryByGoodsId: '/base/erpGoodsFormula/queryByGoodsId',
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    rowSelectChange(record, index) {
      return {
        on: {
          click: (event) => {
            this.selectedFormularId = record.id
            this.model.year = record.year
            this.getFormulaDetailList(record)
          },
        },
      }
    },
    getFormulaDetailList(record) {
      let params = []
      console.log('获取配方明细列表', record)
      params.push(record.id)

      getAction(this.url.formulaDetailList, { formulaIds: params })
        .then((res) => {
          if (res.success) {
            let result = res.result
            this.formulaDetailTable.datasource = res.result
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    onSelectChange(record, selected, selectedRowKeys) {
      console.log('获取的数据',selected, this.selectedRowKeys, record)
      if (selected.length == 0) {
        this.formulaDetailTable.datasource = []
        return
      }
      // selected.forEach((item) => {
      //   params.push(item.id)
      // })
      let ids = this.goodsFormulaTable.datasource.map((item) => item.id)
      selected.forEach((item) => {
        if (ids.indexOf(item.id) == -1) {
          ids.push(item.id)
          this.goodsFormulaTable.datasource.push(item)
        }
      })
      this.selectedFormularId = selected[selected.length - 1].id
      this.goodsFormulaCon.formulaIds = ids
      this.getFormulaDetailList(selected[selected.length - 1])
    },
    //重置查询条件
    searchReset() {
      this.expandedRowKeys = []
      this.queryParam = {
        code:'',
        name:''
      }
      this.getFormulaDatasource();
    },

    onSelectRow(record, selected, selectedRows, nativeEvent) {
      let ids = []
      selected.forEach((item) => {
        ids.push(item.id)
      })
      this.goodsFormulaCon.formulaIds = ids
      if (selected) {
        let param = record.id
        getAction(this.url.formulaDetailList, { formulaCode: param })
          .then((res) => {
            if (res.success) {
              this.formulaDetailTable.datasource = res.result
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = false
          })
        this.dataSourceBack.forEach((item) => {
          if (item.id == record.id) {
            this.formulaDetailTable.datasource.push(item)
          }
        })
      } else {
        // this.selectedRowKeys = this.selectedRowKeys.filter(item => item !== record.id);
        this.checkSelectRows = this.checkSelectRows.filter((item) => item.id != record.id)
      }
    },
    getFormulaDatasource(goodsId) {
      console.log('-------------------')

      if (goodsId) {
        let queryFormulaParams = { goodsId: goodsId }
        //根据物料id查询是否已绑定配方
        getAction(this.url.queryByGoodsId, queryFormulaParams).then((res) => {
          if (res.success) {
            console.log('根据物料id查询是否已绑定BOM', res.result)
            this.goodsFormulaTable.datasource = res.result
            let ids = this.goodsFormulaTable.datasource.map((item) => item.id)
            this.goodsFormulaCon.formulaIds = ids
          }
        })
      }

      let params = {}
      params.pageSize = this.formulaTable.ipagination.pageSize
      params.pageNo = this.formulaTable.ipagination.current
      params.code=this.queryParam.code
      params.name=this.queryParam.name
      getAction(this.url.formulaList, params).then((res) => {
        if (res.success) {
          console.log(res.result.records)
          this.formulaTable.datasource = res.result.records
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //选择员工方法
    handleSelectEmployeeOk(data) {
      console.log('选择员工：', data)
      if (data) {
        // console.log(data);
        // console.log(data.employeeName);
        this.model.belongUser = data.employeeName
        this.$forceUpdate() //重新渲染UI
        // console.log(data.employeeName,this.model.owner);
      }
    },
    //绑定所属员工
    handleSelectEmployee() {
      this.$refs.selectEmployee.visible = true
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/wlbh'
      putAction(url, { name: '物料编号' }).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
        }
      })
    },
    //计算转换率
    safeDivision(numerator, denominator) {
      if (denominator === 0) {
        // 处理除数为0的情况，可以返回错误信息或默认值
        return 'Error: Division by zero'
      }
      console.log('计算')
      // 执行除法并保留两位小数
      return (numerator / denominator).toFixed(6)
    },

    noneSpecChange() {
      try {
        this.model.noneSpec = this.model.noneSpec.toUpperCase().trim()
        let tempSpec = this.model.noneSpec
        let k = tempSpec.indexOf('KG')
        let k1 = tempSpec.indexOf('G')
        if (k > 0) {
          let c = tempSpec.indexOf('*')
          let t1 = tempSpec.substr(0, k)
          let t2 = tempSpec.substr(c + 1)

          let bt1 = Number.parseInt(t1)
          let bt2 = Number.parseInt(t2)

          this.model.packSpec = bt1 * bt2 * 1000

          this.model.coRate = ((bt1 * bt2) / 1000).toFixed(6)
        } else if (k1 > 0) {
          let c = tempSpec.indexOf('*')
          let t1 = tempSpec.substr(0, k1)
          let t2 = tempSpec.substr(c + 1)
          let bt1 = new Big(t1)
          let bt2 = new Big(t2)
          let h = bt1.times(bt2)
          this.model.coRate = h.div(new Big(1000000))
        }
      } catch (e) {}
    },
    onWarehouseSelected(rows) {
      this.model.warehouseCode = rows.code
      this.model.warehouseName = rows.name
    },
    onGoodsCategorySelected(rows) {
      console.log(11111)

      this.model.categoryName = rows.name
      this.model.categoryNo = rows.code
      // 判断是否是成品，并且关联包材，如果是下方显示包材关联表
      let str = rows.name
      let productChar = '成品'
      let packageChar = '包材'
      let otherChar = '原料'
      let containsProductChar = str.includes(productChar)
      let containsPackageChar = str.includes(packageChar)
      let containsOtherChar = str.includes(otherChar)
      console.log('***********************')

      if (containsProductChar) {
        console.log('containsProductChar')
        this.productShow = true
        this.otherShow = false
        this.packageShow = false
      } else if (containsPackageChar) {
        console.log('containsPackageChar')
        this.productShow = false
        this.otherShow = false
        this.packageShow = true
      } else {
        console.log('containsOtherChar')

        this.productShow = false
        this.otherShow = true
        this.packageShow = false
      }
    },
    onChangeShowRow() {
      getAction('/goods/erpGoodsCategory/queryByCode', { code: this.model.categoryNo }).then((res) => {
        let str = res.result.name
        let char = '成品'
        let containsChar = str.includes(char)
        console.log(containsChar)
        console.log(this.model.isAssBc)
        if (containsChar && (this.model.isAssBc === 1 || this.model.isAssBc === '1')) {
          this.productShow = true
          console.log('1')
          console.log(this.productShow)
        } else {
          this.productShow = false
          console.log('2')
          console.log(this.productShow)
        }
      })
    },
    handleSwitchChange(newValue) {
      // newValue 是开关的新值
      console.log('开关的新值:', newValue)
      // 在这里调用你的方法或者进行其他操作
      if (newValue) {
        this.getSequenceNum()
      }
    },
    add(record) {
      // this.edit(this.modelDefault);
      console.log('addrecord')
      console.log(record)
      this.model.id = record[0].id
      this.model.code = record[0].code
      this.model.name = record[0].name
      this.model.noneSpec = record[0].noneSpec
      this.model.year = new Date().getFullYear()
      this.getFormulaDatasource(record[0].id)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      console.log('--------model-----------')
      console.log(this.model)
      console.log(record)

      getAction('/base/erpGoods/queryErpGoodsPackageByMainId', { goodsId: this.model.id }).then((res) => {
        this.model.erpGoodsPackageList = res.result
      })
      this.onChangeShowRow()
    },
    submitForm() {
      const that = this
      this.goodsFormulaCon.goodsId = this.model.id
      this.goodsFormulaCon.year = this.model.year
      // if (this.goodsFormulaCon.formulaIds.length < 1) {
      //   this.$message.error('请选择一个BOM')
      //   return
      // }
      // if (this.goodsFormulaCon.formulaIds.length > 1) {
      //   this.$message.error('最多选择一个BOM')
      //   return
      // }
      // let currentYear = new Date().getFullYear()
      // console.log(currentYear)

      // if (this.goodsFormulaCon.year < currentYear) {
      //   this.$message.error('请确认年份正确')
      //   return
      // }

      console.log('提交配方关联', this.goodsFormulaCon)
      // 触发表单验证

      postAction(this.url.add, this.goodsFormulaCon).then((res) => {
        if (res.success) {
          this.$message.success('添加成功')
        } else {
          this.$message.warning(res)
        }
        that.$emit('ok',this.selectedFormularId)
      })
    },
    // addRowCustom () {
    //   this.orderMainModel.jeecgOrderCustomerList.push({});
    //   this.$forceUpdate();
    // },
    goodsOk(datas) {
      console.log('-----------------------')
      console.log(datas)
      let _this = this
      postAction('/base/erpGoods/list/ids', { ids: datas }).then((res) => {
        console.log(res.result)
        let erpGoodsList = res.result
        erpGoodsList.forEach(function (item, index) {
          console.log(item, index)
          let detail = {}
          detail.packageId = item.id
          detail.packageCode = item.code
          detail.packageName = item.name
          detail.noneSpec = item.noneSpec
          detail.packageType = item.packageType
          detail.materialQuality = item.materialQuality
          console.log(_this.model.erpGoodsPackageList)
          _this.filterPackageId(item.id)
          _this.model.erpGoodsPackageList.push(detail)
        })
      })
    },
    filterPackageId(packageId) {
      this.model.erpGoodsPackageList = this.model.erpGoodsPackageList.filter(function (item) {
        return item.packageId !== packageId
      })
    },
    addMaterielPackage: function () {
      // 新增物料
      // console.log(this.$refs.selectGoodsList)
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
      // this.$refs.selectGoodsList.add();
      // this.$refs.selectGoodsList.title = "新增";
      // this.$refs.selectGoodsList.disableSubmit = false;
    },
    onCellChange(record, dataIndex, value) {
      console.log(this.model.erpGoodsPackageList)
      console.log(record)
      const datasource = [...this.model.erpGoodsPackageList]
      const target = datasource.find((item) => item.packageCode === record.packageCode)
      // console.log(target,key,dataIndex,value)
      if (record) {
        target[dataIndex] = value
        this.model.erpGoodsPackageList = datasource
      }
    },
    onDelete(key) {
      const datasource = [...this.goodsFormulaTable.datasource]
      this.goodsFormulaTable.datasource = datasource.filter((item) => item.id !== key)
      let ids = this.goodsFormulaTable.datasource.map((item) => item.id)
      this.goodsFormulaCon.formulaIds = ids
    },
    copy(record) {
      console.log(record)
      this.model = Object.assign({}, record)
      this.model.id = undefined
      this.model.code = ''
    },
  },
}
</script>
